import 'package:flutter/material.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/utils/image_url.dart';
import 'package:loxen/view/material/material_category_widget.dart';
import 'package:provider/provider.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:loxen/mode/material/material_index_bean.dart';
import 'package:loxen/mode/material/material_item.dart';
import 'package:loxen/mode/material/material_list_bean.dart';
import 'package:loxen/routes/routes.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/viewmode/material_index_viewmodel.dart';
import 'package:loxen/widget/empty_widget.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';

class MaterialIndexWidget extends StatefulWidget {
  const MaterialIndexWidget({Key key}) : super(key: key);

  @override
  _MaterialIndexWidgetState createState() => _MaterialIndexWidgetState();
}

class _MaterialIndexWidgetState extends State<MaterialIndexWidget>
    with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size(double.infinity, 95.h),
        child: Container(
          color: Theme.of(context).primaryColor,
          child: SafeArea(
              child: Center(
            child: Text(
              StringResources.su_cai,
              style: TextStyle(
                  fontSize: 34.sp,
                  color: Theme.of(context).textTheme.subtitle1.color,
                  fontWeight: FontWeight.bold),
            ),
          )),
        ),
      ),
      body: Selector<MaterialIndexViewModel, BaseState>(
          builder: (context, state, __) {
            if (state == BaseState.LOADING) {
              return LoadingWidget();
            }
            if (state == BaseState.FAIL) {
              return FailWidget(
                onClick: () {
                  context.read<MaterialIndexViewModel>().loadData();
                },
              );
            }
            if (state == BaseState.CONTENT) {
              return _contentShow(context);
            }
            if (state == BaseState.EMPTY) {
              return EmptyWidget(
                content: '素材数据空',
              );
            }
            return null;
          },
          selector: (_, model) => model.mState),
    );
  }

  Widget _contentShow(BuildContext context) {
    MaterialIndexBean bean =
        Provider.of<MaterialIndexViewModel>(context, listen: false).materialIndexBean;
    MaterialListBean listBean =
        Provider.of<MaterialIndexViewModel>(context, listen: false).materialListBean;
    return ListView(
      children: <Widget>[
        Container(
          width: double.infinity,
          height: 320.h,
          child: Swiper(
            itemCount: bean.data.banner.length,
            itemBuilder: (_, index) => _getImage(bean.data.banner[index].image),
            autoplay: true,
            pagination: SwiperPagination(
                builder: DotSwiperPaginationBuilder(
                    color: Colors.white38,
                    // 其他点的颜色
                    activeColor: Colors.white,
                    // 当前点的颜色
                    space: 5.w,
                    size: 13.w,
                    activeSize: 18.w // 点与点之间的距离
                    )),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 50.w, top: 39.h),
          child: Text(
            StringResources.fen_lei,
            style: TextStyle(
                fontSize: 32.sp,
                fontWeight: FontWeight.bold,
                color: Theme.of(context).textTheme.subtitle2.color),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 35.w, right: 35.w, top: 18.h),
          child: GridView.builder(
              shrinkWrap: true,
              itemCount: bean.data.category.length,
              physics: NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  //横轴元素个数
                  crossAxisCount: 4,
                  //纵轴间距
                  mainAxisSpacing: 17.w,
                  //横轴间距
                  crossAxisSpacing: 17.w,
                  //子组件宽高长度比例
                  childAspectRatio: 0.623),
              itemBuilder: (context, index) =>
                  _getMaterialType(context, bean.data.category[index])),
        ),
        Padding(
          padding: EdgeInsets.only(left: 50.w, top: 40.h),
          child: Text(
            StringResources.ren_qi_jing_xuan,
            style: TextStyle(
                fontSize: 32.sp,
                fontWeight: FontWeight.bold,
                color: Theme.of(context).textTheme.subtitle2.color),
          ),
        ),
        Padding(
          padding: EdgeInsets.only(left: 35.w, right: 35.w, top: 20.h),
          child: GridView.builder(
            shrinkWrap: true,
            itemCount: listBean.data.results.length,
            physics: NeverScrollableScrollPhysics(),
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                //横轴元素个数
                crossAxisCount: 2,
                //纵轴间距
                mainAxisSpacing: 0,
                //横轴间距
                crossAxisSpacing: 0,
                //子组件宽高长度比例
                childAspectRatio: 1),
            itemBuilder: (context, index) => _getMaterial(context, listBean.data.results[index]),
          ),
        )
      ],
    );
  }

  Widget _getMaterial(BuildContext context, MaterialItem result) {
    return InkWell(
      onTap: () {
        Navigator.of(context).pushNamed(Routes.material_detail, arguments: result.id);
      },
      child: Container(
        child: CachedNetworkImage(
          imageUrl: ImageUrlUtil.getClean(result.cover),
          placeholder: (_, __) => Constants.loadingIcon(),
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  //轮播图
  Widget _getImage(String url) {
    return CachedNetworkImage(
      imageUrl: ImageUrlUtil.getClean(url),
      placeholder: (_, __) => Constants.loadingIcon(),
      fit: BoxFit.cover,
    );
  }

  //素材分类
  Widget _getMaterialType(BuildContext context, Category entity) {
    return InkWell(
      onTap: () {
        // Navigator.of(context).pushNamed(Routes.material_category, arguments: entity.name);
        Navigator.of(context).push(MaterialPageRoute(builder: (_)=>MaterialCategoryWidget(category: entity.name)));
      },
      child: Stack(
        alignment: Alignment.center,
        children: <Widget>[
          ClipRRect(
              borderRadius: BorderRadius.circular(10.w),
              child: CachedNetworkImage(
                imageUrl: ImageUrlUtil.getClean(entity.cover),
                placeholder: (_, __) => Constants.loadingIcon(),
                fit: BoxFit.cover,
              )),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container(
              height: 60.h,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.black26,
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(10.w),
                  bottomRight: Radius.circular(10.w),
                ),
              ),
              child: Text(
                entity.name,
                style: TextStyle(
                    fontSize: 22.sp,
                    color: Theme.of(context).textTheme.subtitle1.color,
                    fontWeight: FontWeight.w500),
              ),
            ),
          )
        ],
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
